<template>
  <el-form label-width="100px" ref="spuFormRef" :model="spuInfo" :rules="spuRules">
    <el-form-item label="SPU名称" prop="spuName">
      <el-input placeholder="请输入SPU名称" v-model="spuInfo.spuName"></el-input>
    </el-form-item>

    <el-form-item label="SPU品牌" prop="tmId">
      <el-select placeholder="请选择" v-model="spuInfo.tmId">
        <el-option v-for="trademark in baseTrademarkList" :key="trademark.id" :label="trademark.tmName"
          :value="trademark.id" />
      </el-select>
    </el-form-item>

    <el-form-item label="SPU描述" prop="description">
      <el-input :rows="4" type="textarea" v-model="spuInfo.description" />
    </el-form-item>

    <el-form-item label="SPU图片" prop="spuImageList">
      <el-upload list-type="picture-card" v-model:file-list="fileList" :action="`${BASE_URL}/admin/product/upload`"
        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" class="avatar" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性" prop="spuSaleAttrList">
      <el-select v-model="spuInfo.spuSaleAttr" :placeholder="`还有${filterBaseSaleAttrList.length}项未选择`">
        <el-option v-for="saleAttr in filterBaseSaleAttrList" :key="saleAttr.id" :label="saleAttr.name"
          :value="saleAttr.name" />
      </el-select>
      <el-button type="primary" :icon="Plus" style="margin-left:6px;" @click="addSaleValue"
        :disabled="!spuInfo.spuSaleAttr">添加销售属性</el-button>
      <el-table border style="margin:16px 0;" :data="spuInfo.spuSaleAttrList">
        <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
        <el-table-column label="属性名" prop="saleAttrName" align="center" width="160"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{ row }">
            <el-tag v-for="saleAttrValue in row.spuSaleAttrValueList" :key="saleAttrValue.saleAttrValueName"
              class="mx-1" closable :disable-transitions="false" @close="handleClose(row, saleAttrValue)"
              style="margin-right: 3px;">
              {{ saleAttrValue.saleAttrValueName }}
            </el-tag>
            <el-input v-if="row.inputVisible" ref="InputRef" v-model="inputValue" class="ml-1 w-20" size="small"
              @keyup.enter="handleInputConfirm(row)" @blur="handleInputConfirm(row)" style="width:60px" />
            <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(row)">
              + New Tag
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row, $index }">
            <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled" title="确定删除该项销售属性吗?"
              @confirm="confirmEvent($index)" @cancel="cancelEvent">
              <template #reference>
                <el-button :icon="Delete" type="danger" size="small" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-button type="primary" @click="submitForm(spuFormRef)">保存</el-button>
      <el-button @click="toSpuList">取消</el-button>

    </el-form-item>

  </el-form>
</template>

<script lang="ts">
export default {
  name: "SpuForm"
}
</script>
<script setup lang="ts">
import { Plus, Delete } from '@element-plus/icons-vue';
import { ref, onMounted, reactive, computed } from 'vue'
import type { UploadProps, UploadUserFile, FormInstance, FormRules } from 'element-plus'
import { reqGetSpuFormBaseTrademarkList, reqGetSpuFormBaseSaleAttrList, ReqSaveSpuInfo, reqGetSpuImageList, reqGetSpuSaleAttrList, reqUpdateSpuInfo } from "@/api/product/spu"
import { InfoFilled } from '@element-plus/icons-vue'
import { nextTick } from 'vue'
import { ElMessage, ElInput } from 'element-plus'
import { ShowStatus } from '../types';
import { useCategoryListStore } from '@/stores/categorySelectorList';
import Item from '@/layout/components/Sidebar/Item';

// 接收父组件传递的数据 实现组件切换
const emits = defineEmits(["setShowStatus"])
// 接收父组件传递的数据 实现数据回显
const props = defineProps(["currentSpuInfo"])

// 创建store
const categorySelectorList = useCategoryListStore()

// 11.添加数据 的 校验规则
const formSize = ref('default')
const spuFormRef = ref<FormInstance>()

const spuRules = reactive<FormRules>({
  spuName: [
    { required: true, message: '请输入SPU名称', trigger: 'blur' },
    { min: 1, max: 10, message: 'SPU名称在1-10个字符之间', trigger: 'blur' }
  ],
  tmId: [{ required: true, message: '请选择SPU品牌', trigger: 'blur' }],
  description: [{ required: true, message: '请输入SPU描述', trigger: 'blur' }],
  spuImageList: [{ required: true, message: '请选择一张图片', type: 'array', trigger: 'change' }],
  spuSaleAttrList: [{ required: true, message: '请至少添加一个属性', type: 'array', trigger: 'click' }]
})



// 1.上传图片 需要的 数据
const fileList = ref<UploadUserFile[]>([])
const imageUrl = ref('')
const BASE_URL = import.meta.env.VITE_API_URL;
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 2.spuform中的spu品牌数据
const baseTrademarkList = ref([])
// 3.spuform中的销售属性 数据
const baseSaleAttrList = ref([])
// 4.追加 需准备的spuInfo数据
const spuInfo = reactive({
  spuName: "", //品牌名称
  description: "",//描述
  tmId: "",//spu品牌
  category3Id: 0,
  spuImageList: [],//上传图片数据
  spuSaleAttrList: [],//销售属性
  spuSaleAttr: "",//自定义属性 绑定销售属性
  ...props.currentSpuInfo
})
// 5.tag标签 需要的数据
const inputValue = ref('')
const dynamicTags = ref(['Tag 1', 'Tag 2', 'Tag 3'])
// const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()






// 1.页面一加载就获取数据
onMounted(async () => {
  // 1.1同时发送两个请求 使用promise中的all方法 
  try {
    // 添加时的两个请求
    let promises = [reqGetSpuFormBaseTrademarkList(), reqGetSpuFormBaseSaleAttrList()]

    const { id } = spuInfo
    // 1.2 判断是否有id 来辨别是添加请求 还是 编辑请求
    if (id) {
      //  存在id就是编辑 请求
      promises = promises.concat([reqGetSpuImageList(id), reqGetSpuSaleAttrList(id)])
    }
    // 1.3 同时发送四个请求 获取数据
    const [responseBaseTrademarkList, responseBaseSaleAttrList, responseSpuImageList, responseSpuSaleAttrList] = await Promise.all(promises)
    // 1.4 设置 添加 数据
    baseTrademarkList.value = responseBaseTrademarkList
    baseSaleAttrList.value = responseBaseSaleAttrList

    console.log("11111", responseSpuImageList, responseSpuSaleAttrList)
    // 1.5 判断 是否为 编辑 请求
    if (responseSpuImageList && responseSpuSaleAttrList) {
      // 设置数据
      spuInfo.spuImageList = responseSpuImageList
      // 实现图片显示
      fileList.value = responseSpuImageList.map(item => {
        return {
          ...item,
          name: item.imgName,
          url: item.imgUrl
        }
      })
      spuInfo.spuSaleAttrList = responseSpuSaleAttrList
    }
  } catch (error) {
    ElMessage.error("获取数据失败!")
  }
})
//2. 图片上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  //  追加 图片属性
  spuInfo.spuImageList.push({
    imgName: uploadFile.name,
    imgUrl: response.data,
  })

  // 清空校验规则
  spuFormRef.value!.clearValidate(['spuImageList'])
}

//3.删除 上传的图片
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)  uploadFiles剩余图片
  // 使用map遍历 重新赋值
  // console.log(uploadFiles)
  spuInfo.spuImageList = uploadFiles.map(item => {
    return {
      imgName: item.name,
      imgUrl: item.response.data,
    }
  })


}

// 图片预览
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

//  图片上传前的校验规则
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imgurlType = ['image/jpeg', 'image/gif', 'image/jpg']
  // 如果上传的图片类型不包括在imgurlType中
  if (!imgurlType.includes(rawFile.type)) {
    ElMessage.error('上传的图片必须是jepg、gif、jpg格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传的图片格式不能大于2M!')
    return false
  }
  return true
}

// 4.点击 +添加销售属性按钮
const addSaleValue = () => {
  // 4.1 判断 是否有属性名且存在属性值
  const spuSaleAttrList = spuInfo.spuSaleAttrList
  if (spuSaleAttrList.length && spuSaleAttrList.some(item => item.spuSaleAttrValueList.length == 0
  )) {
    ElMessage.error("请输入该属性对应的属性值")
    return
  }
  // 4.2 统一添加 baseSaleAttrId （销售属性与属性值）
  const id = baseSaleAttrList.value.find(item => item.name == spuInfo.spuSaleAttr).id
  // 4.3向 spuSaleAttrList中追加数据
  spuInfo.spuSaleAttrList.push({
    baseSaleAttrId: id,
    saleAttrName: spuInfo.spuSaleAttr,
    spuSaleAttrValueList: [],
    inputVisible: false
  })
  // 4.2 清空上一次的值
  spuInfo.spuSaleAttr = ""

  // 清空校验规则
  spuFormRef.value!.clearValidate(['spuImageList'])
}

// 5.实现销售属性添加到下面的表格后的删除效果
const filterBaseSaleAttrList = computed(() => {
  return baseSaleAttrList.value.filter(item => {
    return !spuInfo.spuSaleAttrList.find(saleAttr => saleAttr.saleAttrName === item.name)
  })
})

// 6.点击 spuSaleAttrList中的 删除icon 
const confirmEvent = (index: number) => {
  //  6.1删除 销售属性值
  spuInfo.spuSaleAttrList.splice(index, 1)
  // 6.2删除成功提示
  ElMessage.success("删除成功")
}
// 7.取消删除
const cancelEvent = () => {
  ElMessage.info("取消删除")
}
// 8.点击tag标签添加属性值数据
const showInput = (row) => {
  // 8.1显示输入框
  row.inputVisible = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

// 9.删除添加的某项属性值
const handleClose = (row, saleAttrValue) => {
  // dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
  // 9.1删除属性值
  row.spuSaleAttrValueList.splice(row.spuSaleAttrValueList.indexOf(saleAttrValue), 1)
}


// 10.确定 追加 的属性值 数据
const handleInputConfirm = (row) => {
  // 10.1 判断添加的属性值是否存在一样的
  if (inputValue.value) {
    // 该属性值列表有值且存在一样的数据
    const spuSaleAttrValueList = row.spuSaleAttrValueList
    if (spuSaleAttrValueList.length && spuSaleAttrValueList.some(item => item.saleAttrValueName === inputValue.value)) {
      ElMessage.warning("请输入不同的属性值！")
      row.inputVisible = false
      inputValue.value = ''
      return
    }

    // dynamicTags.value.push(inputValue.value)
    // 10.3添加 数据
    row.spuSaleAttrValueList.push({
      // 10.2 统一添加 baseSaleAttrId
      baseSaleAttrId: row.baseSaleAttrId,
      isChecked: 0,
      saleAttrName: row.saleAttrName, //销售属性名称
      saleAttrValueName: inputValue.value,//销售属性值名称
    })
  }
  row.inputVisible = false
  inputValue.value = ''
}
// 11.点击 保存 按钮
const submitForm = async (formEl: FormInstance | undefined) => {

  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {

      //11.1发送请求 添加数据
      spuInfo.category3Id = categorySelectorList.category3Id as number
      // 判断是否存在id
      if (spuInfo.id) {
        // 存在id就是 编辑请求
        await reqUpdateSpuInfo(spuInfo)
      } else {
        // 否则就是 添加请求
        await ReqSaveSpuInfo(spuInfo)
      }

      // 11.2 消息提示
      ElMessage.success("操作数据成功！")

      //11.3 跳转到 spulist页面
      emits("setShowStatus", ShowStatus.SHOW_SPU)
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 12. 点击 取消按钮 跳转到spulist
const toSpuList = () => {
  emits("setShowStatus", ShowStatus.SHOW_SPU)
}






</script>


<style>

</style>